<template>
  <d2-container>

    <template slot="header">
      <el-form :gutter="24" ref="search-box" :model="mainQuery"  label-position="left" :inline="true">
        <el-col :span="8">
          <el-form-item label="商户号：" size="mini">
            <el-input placeholder="" v-model="mainQuery.mchNo" @keyup.enter.native="handleSearch" size="small" clearable></el-input>
          </el-form-item>    
        </el-col>

        <el-col :span="8">
          <el-form-item label="终端号：" size="mini">
            <el-input placeholder="" v-model="mainQuery.terNo" @keyup.enter.native="handleSearch" size="small" clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="订单号：" size="mini">
            <el-input placeholder="" v-model="mainQuery.tradeNo" @keyup.enter.native="handleSearch" size="small" clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="投诉级别" size="mini" prop="type">
            <el-select v-model="mainQuery.level" size="small" clearable>
              <el-option
                v-for="item in complaintLevelOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="处理状态" size="mini" prop="type">
            <el-select v-model="mainQuery.handleStatus" size="small" clearable>
              <el-option
                v-for="item in complaintHandleStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-form-item label="时间区间：" size="mini">
          <el-date-picker
            size="small" 
            v-model="dateTimeRange"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="datetimePickerOptions"
            @change="onDateTimePickerChange"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <div class="search-btn-box">
        <div class="left">

          <el-button-group>
            <el-button class="filter-item" icon="el-icon-circle-plus" type="success" @click="handleAdd" :loading="mainTable.loading" size="mini" v-if="$options.filters['checkButtonAccess']('tradeordercomplaint-add')">添加</el-button>
            <el-button class="filter-item" type="primary" @click="handleReview(2)" :loading="mainTable.loading" size="mini"  v-if="$options.filters['checkButtonAccess']('tradeordercomplaint-handlestatus')">已处理</el-button>
            <el-button class="filter-item" type="danger" @click="handleReview(3)" :loading="mainTable.loading" size="mini"  v-if="$options.filters['checkButtonAccess']('tradeordercomplaint-handlestatus')">商户自行协商</el-button>
            <el-button class="filter-item" icon="el-icon-download" size="mini" @click="handleExportExcel">导出</el-button>
          </el-button-group>

          <el-button-group v-if="$options.filters['checkButtonAccess']('tradeordercomplaint-upload')" style="margin-left: 30px;">
            <el-button class="filter-item" icon="el-icon-upload" type="plain" @click="handleUpload" :loading="mainTable.loading" size="mini">批量投诉</el-button>
            <el-button class="filter-item" icon="el-icon-download" type="plain" @click="handleDownloadTemplate" :loading="mainTable.loading" size="mini">下载模板</el-button>
          </el-button-group>
          
        </div>
        <div class="right">
          <el-button class="filter-item" icon="" type="default" @click="resetMainData" :loading="mainTable.loading" size="small">重置</el-button>
          <el-button class="filter-item" icon="el-icon-search" type="primary" @click="handleSearch" :loading="mainTable.loading" size="small">查询</el-button>
        </div>
      </div>
    </template>

    <!--主列表数据-->
    <d2-crud
      ref="d2Crud"
      selection-row
      :options="mainTable.options"
      :index-row="mainTable.indexRow"
      :columns="mainTable.columns"
      :data="mainTable.list"
      :loading="mainTable.loading"
      :rowHandle="mainTable.rowHandle"
      @current-change="onMainCurrentChange"
      @custom-emit-handle-order="handleOrderDetail"
      @custom-emit-handle-record="handleRecord"
      @selection-change="onMainSelectionChange"
    ></d2-crud>

    <template slot="footer">
      <el-pagination
        @size-change="handleMainSizeChange"
        @current-change="handleMainPageChange"
        :current-page="mainTable.pagination.currentPage"
        :page-sizes="mainTable.pagination.pageSizes"
        :page-size="mainTable.pagination.pageSize"
        :page-count="mainTable.pagination.pageCount"
        :total="mainTable.pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        :background="true"
        >
      </el-pagination>
    </template>

    <dialog-add ref="dialog-add" @dialog-close="fetchMainData"></dialog-add>

    <dialog-detail ref="dialog-detail" @dialog-close="fetchMainData"></dialog-detail>

    <dialog-upload ref="dialog-upload" @dialog-close="fetchMainData"></dialog-upload>

    <dialog-handle-record ref="dialog-handle-record" @dialog-close="fetchMainData"></dialog-handle-record>

    <common-export ref="common-export"></common-export>

  </d2-container>
</template>

<script>

import ApiMain from '@/api/trade.complaint';
import DialogAdd from './dialog-add';
import DialogUpload from './dialog-upload';
import DialogDetail from '../detail/dialog-add';
import DialogHandleRecord from './dialog-handle-record';
import CommonExport from '../../common/export';
import util from '@/libs/util.js';
import { complaintLevelOptions, complaintHandleStatusOptions } from '@/const/constant';
import DatetimePickerMixin from '@/mixin/DatetimePickerMixin'


export default {
  name: 'trade-complaint',
  mixins: [
    DatetimePickerMixin,
  ],
  components: {
    'dialog-add': DialogAdd,
    'dialog-detail': DialogDetail,
    'dialog-upload': DialogUpload,
    'dialog-handle-record': DialogHandleRecord,
    'common-export': CommonExport,
  },
  data () {
    return {

      mainQuery: {
        mchNo: '',
        terNo: '',
        tradeNo: '',
        level: '',
        handleStatus: '',
        startTime: '',
        endTime: ''
      },

      mainTable: {
        loading: false,
        options: {
          border             : true,
          stripe             : true,
          highlightCurrentRow: true,
          emptyText          : '暂无数据',
          size               : 'mini',
        },
        // indexRow: {
        //   title:'序号',
        //   width: "80",
        //   align:'center'
        // },
        indexRow: null,
        allowSelect: false,
        columns: [
          // {title: 'id', key: 'id', align: 'center', showOverflowTooltip: true},
          {title: '单号', key: 'tradeNo', align: 'center', width: '180', showOverflowTooltip: true, fixed: true},
          {title: '商户号', key: 'mchNo', align: 'center', width: '180', showOverflowTooltip: true},
          {title: '终端号', key: 'terNo', align: 'center', width: '180', showOverflowTooltip: true},
          {title: '交易金额', key: 'mchTransAmount', align: 'center', width: '120', showOverflowTooltip: true, formatter(row, column, cellValue, index) {
            return row.mchTransCurrency + ' ' + row.mchTransAmount / 100
          }},
          {title: '投诉日期', key: 'complaintTime', align: 'center', width: '180', showOverflowTooltip: true},
          {title: '投诉问题', key: 'transReason', align: 'center', width: '120', showOverflowTooltip: true},
          {title: '投诉级别', key: 'strLevel', align: 'center', width: '120', showOverflowTooltip: true},
          {title: '投诉处理状态', key: 'strHandleStatus', align: 'center', width: '120', showOverflowTooltip: true},
          {title: '投诉补充说明', key: 'remark', align: 'center', width: '120', showOverflowTooltip: true},
          {title: '投诉处理截止日期', key: 'handleUtilTime', align: 'center', width: '180', showOverflowTooltip: true},
          {title: '创建人', key: 'createBy', align: 'center', width: '120', showOverflowTooltip: true},
          {title: '创建时间', key: 'createTime', align: 'center', width: '180', showOverflowTooltip: true},
          {title: '处理人', key: 'reviewBy', align: 'center', width: '120', showOverflowTooltip: true},
          {title: '处理时间', key: 'reviewTime', align: 'center', width: '180', showOverflowTooltip: true},
          {title: '商户处理结果', key: 'handleResult', align: 'center', width: '120', showOverflowTooltip: true, formatter(row, column, cellValue, index) {
            let split = row.handleResult.split('###')
            return split.length > 0 ? split[0] : ''
          }},
        ],
        rowHandle: {
          width: '250',
          align: 'center',
          fixed: 'right',
          custom: [
            {
              text: '查看订单',
              type: 'primary',
              size: 'mini',
              emit: 'custom-emit-handle-order'
            },
            {
              text: '处理过程记录',
              type: 'default',
              size: 'mini',
              emit: 'custom-emit-handle-record'
            },
          ]
        },
        list: [],
        pagination: {
          currentPage: 1,
          pageSize   : 50,
          total      : 0,
          pageSizes  : [50, 100, 200]
        },
        selectionRow: [],
      },

      complaintLevelOptions: complaintLevelOptions, 
      complaintHandleStatusOptions: complaintHandleStatusOptions,
      dateTimeRange: []
    }
  },
  mounted () {
    this.resetMainData();
  },
  beforeDestroy () {
  },
  methods: {

    handleSearch () {
      this.mainTable.pagination.currentPage = 1;
      this.fetchMainData();
    },

    renderMainData (re) {
      this.mainTable.list = re.list;
      this.mainTable.pagination.total = re.total;
    },

    handleMainSizeChange (val) {
      this.mainTable.pagination.pageSize = val;
      this.mainTable.pagination.currentPage = 1;
      this.fetchMainData()
    },
    
    handleMainPageChange (val) {
      this.mainTable.pagination.currentPage = val;
      this.fetchMainData()
    },

    buildMainQuery () {

      var query = {
        page  : this.mainTable.pagination.currentPage,
        limit : this.mainTable.pagination.pageSize,
        search: this.mainQuery,
      };

      return query;
    },

    resetMainData () {

      this.mainQuery = {
        mchNo: '',
        terNo: '',
        tradeNo: '',
        level: '',
        handleStatus: '',
        startTime: '',
        endTime: ''
      };

      this.fetchMainData();
    },

    async fetchMainData () {

      this.mainTable.loading = true;

      try {
        var re = await ApiMain.list(this.buildMainQuery());
        this.renderMainData(re);
      } catch (err) {}

      this.mainTable.loading = false;

    },

    onDateTimePickerChange() {
      this.mainQuery.startTime = this.dateTimeRange && this.dateTimeRange.length > 0 ? this.dateTimeRange[0] : ''
      this.mainQuery.endTime = this.dateTimeRange && this.dateTimeRange.length > 0 ? this.dateTimeRange[1] : ''
    },

    onMainCurrentChange (now, old) {
      this.mainTable.current = now;
    },

    onMainSelectionChange (now, old) {
      this.mainTable.selectionRow = now
    },

    onMainDoubleClick (now) {
      this.mainTable.current = now;
      this.handleSet();
    },

    handleAdd () {
      this.$refs['dialog-add'].show();
    },

    handleSet () {
      if (this.mainTable.current) {
        this.$refs['dialog-add'].show(this.mainTable.current.id);
      }
    },

    handleExportExcel () {
      this.$refs['common-export'].handleExportExcel(ApiMain, this.mainQuery);
    },

    handleUpload () {
      this.$refs['dialog-upload'].show();
    },

    handleDownloadTemplate () {
      window.open(util.getDownloadTemplate('complaint'), '_blank');
    },

    handleOrderDetail ({index, row}) {
      this.$refs['dialog-detail'].show(row.orderId);
    },

    handleRecord ({index, row}) {
      this.$refs['dialog-handle-record'].show(row);
    },

    handleReview (handleStatus) {

      if (this.mainTable.selectionRow.length == 0) {
        this.$message({message: '请选择行', type: 'error'});
        return;
      }
      this.$confirm('确定操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doHandleReview(handleStatus)
      });

    },

    async doHandleReview (handleStatus) {
      
      let ids = []
      for (var i in this.mainTable.selectionRow) {
        ids.push(this.mainTable.selectionRow[i].id);
      }
      await ApiMain.handleStatus({ ids: ids.join(','), handleStatus: handleStatus });
      this.$message({message: '操作成功', type: 'success'});
      this.mainTable.selectionRow = [];
      this.fetchMainData();
    
    },

  }
}
</script>

<style>

</style>
